package com.mrwang.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mrwang.PageResult;
import com.mrwang.mapper.BrandMapper;
import com.mrwang.pojo.Brand;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BrandService {
    @Resource
    BrandMapper brandMapper;

    public PageResult<Brand> brandByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        Example example=new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(key)){
            criteria.andLike("name","%"+key+"%").orEqualTo("letter",key);
        }
        PageHelper.startPage(page,rows);
        if (!StringUtils.isEmpty(sortBy)){
            example.setOrderByClause(sortBy+" "+(desc?"desc":"asc"));
        }
        List<Brand> brands = brandMapper.selectByExample(example);
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
    }

    public void saveBrand(Brand brand, List<Long> cids) {
        brandMapper.insertSelective(brand);
        cids.forEach(cid ->{
            brandMapper.insertCategoryAndBrand(cid,brand.getId());
        });
    }

    public List<Brand> brandByCid(Long cid) {
        return brandMapper.brandByCid(cid);
    }

    public Brand queryBrandInfoById(Long brandId) {
        return brandMapper.selectByPrimaryKey(brandId);
    }
}
